package com.guiwu.caiguanlin.leetcode;

import java.util.*;

/**
 * 删除有序数组中的重复项
 */
public class Test26 {

    public static void main(String[] args) {
//        int[] nums = {1, 1, 2};
        int[] nums = {0,0,1,1,1,2,2,3,3,4};
        int count = removeDuplicates2(nums);
        System.out.println(count);
    }

    /**
     * 自己写
     *
     * @param nums
     * @return
     */
    public static int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                continue;
            }
            map.put(num, num);
            list.add(num);
        }
        Object[] objects = list.stream().sorted().toArray();
        for (int i = 0; i < objects.length; i++) {
            nums[i] = (int) objects[i];
        }
        return objects.length;
    }

    /**
     * 双指针
     * 注意：是有序数组
     *
     * @param nums
     * @return
     */
    public static int removeDuplicates2(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        int count = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] != nums[i + 1]) {
                nums[count + 1] = nums[i + 1];
                count++;
            }
        }
//        Arrays.stream(nums).forEach(System.out::println);
        return count + 1;
    }
}
